package com.lemon.smartsafetynew.ui.activity.base;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lemon.smartsafety.R;
import com.lemon.smartsafety.entity.event.base.AppEvent;
import com.lemon.smartsafety.utils.common.FileUtil;
import com.lemon.smartsafety.utils.common.KeyBoardUtils;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.view.SwipeBackLayout;
import com.lemon.smartsafetynew.ui.activity.record.RecordSafeTrainDetailActivity;
import com.lemon.smartsafetynew.util.common.MyIntent;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.lang.reflect.Field;

import butterknife.Bind;
import okhttp3.Call;

/**
 * Created by SilenceDut on 2015/12/8.
 */
public abstract class SwipeBackActivity extends BaseActivity {
    private LoggerHelper loggerHelper = new LoggerHelper(SwipeBackActivity.class);


    @Nullable @Bind(R.id.swipeBackLayout)
    SwipeBackLayout mSwipeBackLayout;

    @Nullable
    @Bind(R.id.main_title)
    protected TextView mMainTitle;

    @Bind(R.id.toolbar)
    public Toolbar mToolBar;


    /**
     * 设置标题栏
     */
    protected abstract void initTitle();

    /**
     * 结束Activity方法回掉
     */
    protected abstract void callFinish();

    @Override
    protected void initViews() {
        if (mToolBar == null) {
            mToolBar = getViewById(R.id.toolbar);
        }
        if (mSwipeBackLayout == null) {
            mSwipeBackLayout = getViewById(R.id.swipeBackLayout);
        }
        initToolBar();
        if (null != mSwipeBackLayout) {
            mSwipeBackLayout.setCallBack(new SwipeBackLayout.CallBack() {
                @Override
                public void onFinish() {
                    callFinish();
                }
            });
        }

    }

    protected void setBarTitle(int title) {
        this.setBarTitle(getString(title));
    }


    protected void setBarTitle(String title) {
        if (mMainTitle != null) {
            mToolBar.setTitle("");
            mMainTitle.setText(title);
        } else {
            mToolBar.setTitle(title);
        }
    }

    @Subscribe
    public void onEventMainThread(AppEvent event) {
    }

    protected void initToolBar() {
        initTitle();
        setSupportActionBar(mToolBar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyBoardUtils.closeSoftInput(SwipeBackActivity.this);
                callFinish();
            }
        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            callFinish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void getBundleArgs() {

    }

    /**
     * 描述:   修改Tab栏，下横线的长度
     * @param tabs
     * @param leftDip
     * @param rightDip
     */
    protected void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }

    //文件展示
    public void downloadAndShowFile(String urls, String names, Context context, String modeNmae) {
        String fielname="";
        try {
            if(!TextUtils.isEmpty(urls)){
                String url[] = urls.split("/");
                if(!TextUtils.isEmpty(names) && url.length > 0){
                    String name[] = names.split("\\.");
                    fielname = modeNmae+"_"+name[0]+"_"+url[url.length-1];
                }else{
                    fielname = modeNmae+"_"+"附件"+"_"+url[url.length-1];
                }
                File file = new File(FileUtil.getAppOneComOneDocDir(context)+ File.separator + fielname);
                if(!file.exists()) {
                    getFile(urls, fielname,context);
                }else{
                    showFiles(fielname,file);
                }
            }else{
                mHUDUtil.showErrorTip("该文件地址有误!");
            }
        }catch (Exception e){
            mHUDUtil.showErrorTip("该文件地址有误!");
        }
    }

    private void getFile(String fileUrl, final String fileName,Context contxt) {
        mHUDUtil.showHUD();
        OkHttpUtils
                .get()
                .url(fileUrl)
                .build()
                .execute(new FileCallBack(FileUtil.getAppOneComOneDocDir(contxt), fileName) {
                    @Override
                    public void onError(Call call, Exception e) {
                        mHUDUtil.showErrorTip("获取文件失败。");
                    }

                    @Override
                    public void onResponse(File response) {
                        showFiles(fileName,response);
                    }

                    @Override
                    public void inProgress(float progress, long total) {
                        if(progress == 1.0){
                            mHUDUtil.hidden();
                        }
                    }
                });
    }

    //文件的预览
    private void showFiles(String fileName, File response) {
        Intent intent = null;
        if (fileName.endsWith(".xlsx") || fileName.endsWith(".xls")
                || fileName.endsWith(".XLSX") || fileName.endsWith(".XLS")){
            intent = MyIntent.getExcelFileIntent(response.getPath());
        } else if(fileName.endsWith(".txt") || fileName.endsWith(".TXT")){
            intent = MyIntent.getTextFileIntent(response.getPath(),false);
        } else if(fileName.endsWith(".doc") || fileName.endsWith(".docx")
                || fileName.endsWith(".DOC") || fileName.endsWith(".DOCX")){
            intent = MyIntent.getWordFileIntent(response.getPath());
        } else if(fileName.endsWith(".ppt") || fileName.endsWith(".PPT")
                || fileName.endsWith(".pptx") || fileName.endsWith(".PPTX") ){
            intent = MyIntent.getPptFileIntent(response.getPath());
        } else if(fileName.endsWith(".pdf") || fileName.endsWith(".PDF")){
            intent = MyIntent.getPdfFileIntent(response.getPath());
        } else if(fileName.endsWith(".png") || fileName.endsWith(".PNG")
                || fileName.endsWith(".jpg") || fileName.endsWith(".JPG")
                || fileName.endsWith(".jpeg") || fileName.endsWith(".JPEG")){
            intent = MyIntent.getImageFileIntent(response.getPath());
        } else if(fileName.endsWith(".mp4") || fileName.endsWith(".MP4")){
            intent = MyIntent.getVideoFileIntent(response.getPath());
        } else if(fileName.endsWith(".wma") || fileName.endsWith(".wav") || fileName.endsWith(".mp3") ){
            intent = MyIntent.getAudioFileIntent(response.getPath());
        } else {
            intent = null;
        }

        try {
            if(intent != null) {
                startActivity(intent);
            } else {
                mHUDUtil.showErrorTip("未能识别此类文件！");
            }
        } catch (Exception e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mHUDUtil.showErrorTip("没有相应工具打开此类文件，请下载相关App查看此类文件！");
                }
            });
        }
    }
}
